package com.erp.module.pieceworkGrouping

import android.annotation.SuppressLint
import android.app.Activity
import android.bluetooth.BluetoothDevice
import android.content.Intent
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.EditText
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.LinearLayoutManager
import com.erp.CaptureActivity
import com.erp.R
import com.erp.bean.PieceworkcollBean
import com.erp.mclass.QuanXian
import com.erp.module.pieceworkGrouping.PieceworkChaxun.PieceworkChaxunActivity
import com.erp.module.pieceworkGrouping.PieceworkGroupingXz.PieceworkGroupingXzAcitivity
import com.erp.myAdapter.ArrayAdapter
import com.erp.myAdapter.BlueListAdapter
import com.erp.myFragment.BaseKFragment
import com.erp.util.Myutil
import com.erp.view.PullToRefreshView
import com.scanner.scannersdk.MainScannerSdk
import com.scanner.scannersdk.SdkValue
import com.scanner.scannersdk.callback.DicoverBuetoothCallback
import com.scanner.scannersdk.callback.SdkMessage
import kotlinx.android.synthetic.main.dialog_bluelist.bluelist_recycler

import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.UnsupportedEncodingException
import java.nio.charset.Charset
import java.util.Arrays
import com.erp.myAdapter.PieceworkcollAdapter
import com.erp.permission.PermissionListener
import com.erp.util.FileUtils
import com.erp.util.PermissionUtils
import kotlinx.android.synthetic.main.fragment_piecework_grouping.*


class FragmentPieceworkGrouping : BaseKFragment(),PieceworkGroupingContract.PieceworkGroupingFragmentView, View.OnClickListener, PullToRefreshView.OnHeaderRefreshListener, PullToRefreshView.OnFooterRefreshListener, AdapterView.OnItemLongClickListener {
    lateinit var P : PieceworkGroupingContract.ProductionFragmentKP
    var mainScannerSdk: MainScannerSdk? = null
    lateinit var bluelist : MutableList<BluetoothDevice>
    lateinit var PieceworkList : MutableList<PieceworkcollBean>
    //蓝牙选择对话框的列表适配器
    lateinit var blueListAdapter: BlueListAdapter
    lateinit var bluedialog : AlertDialog
    var updialog: AlertDialog?=null
    lateinit var pgadapter : PieceworkcollAdapter
    lateinit var scanlist : MutableList<String>
    lateinit var listAdapter : ArrayAdapter<String>
    lateinit var printerSign :String
    var lastcode :String = ""
    override fun getLayoutId(): Int {
        return R.layout.fragment_piecework_grouping
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun initData() {
        scanlist = ArrayList()
        listAdapter = ArrayAdapter(activity,R.layout.simple_at_item,scanlist)
        LvHuancun.adapter = listAdapter
        LvHuancun.onItemLongClickListener = this
        PieceworkList = ArrayList()
        pgadapter = PieceworkcollAdapter(PieceworkList,activity!!)
        LvPieceworkcoll.adapter = pgadapter
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        P = PieceworkGroupingP(this,context!!,PieceworkList)
        BtBlue.setOnClickListener(this)
        BtFenzu.setOnClickListener(this)
        BtChaxun.setOnClickListener(this)
        MainScannerSdk.initSdk(activity!!.application)
        mainScannerSdk = MainScannerSdk.getInstence()
        //设置为SPP模式
        mainScannerSdk?.model = SdkValue.MODE_BLURTOOTHSPP
        //获取蓝牙列表
        bluelist = arrayListOf()
        blueListAdapter = BlueListAdapter(this, bluelist)
        Pull.setOnHeaderRefreshListener(this)
        Pull.setOnFooterRefreshListener(this)
        BtScan.setOnClickListener(this)
        Pull.setheader(true)
        Pull.headerRefreshing()
        P.getPiecework()
        BtShangchuan.setOnClickListener(this)
        gethuancun()
        printerSign = sp.getString("printerSign","").toString()
    }
    override fun setData(data : String){
        editor.putString("printerSign",data)
        editor.commit()
        printerSign = data
    }

    override fun onClick(v: View?) {
        when(v){
            BtBlue -> {
//                blueDialog()
                PermissionUtils.isdingwei(activity!!, object : PermissionListener {
                    override fun onSucceed(requestCode: Int, grantPermissions: List<String>) {
                        mainScannerSdk?.getBlueToothList(DicoverBuetoothCallback { inBluetoothDeviceList ->
                            bluelist.clear()
                            bluelist.plusAssign(inBluetoothDeviceList)
                            blueListAdapter.notifyDataSetChanged()
                        }, activity)
                        blueDialog()
                    }

                    override fun onFailed(requestCode: Int, deniedPermissions: List<String>) {
                        Myutil.MyTost("没有权限，无法获取蓝牙")
                    }
                })

            }
            BtFenzu -> {
                val intent = Intent()
                intent.setClass(activity!!, PieceworkGroupingXzAcitivity::class.java)
                intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
                startActivityForResult(intent, 100)
            }
            BtScan -> {
                PermissionUtils.issaomiao(activity!!, object : PermissionListener {
                    override fun onSucceed(requestCode: Int, grantPermissions: List<String>) {
                        val intent = Intent()
                        intent.setClass(activity!!, CaptureActivity::class.java)
                        intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
                        startActivityForResult(intent, 1)
                    }

                    override fun onFailed(requestCode: Int, deniedPermissions: List<String>) {
                        Myutil.MyTost("没有权限，无法扫描")
                    }
                })
            }
            BtChaxun -> {
                val intent = Intent()
                intent.setClass(activity!!, PieceworkChaxunActivity::class.java)
                intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
                startActivity(intent)
            }
            BtShangchuan -> {
                if(scanlist.size > 0){
                    updialog = Myutil.showupdatedialog(activity, "正在上传", false)
                    P.postPieceworkcoll(scanlist[0],true)
                }
            }
        }
    }

    override fun getPieceworkOk(gangwei_name : String) {
        TvGangweiName.text = gangwei_name
    }

    override fun getPieceworkNo() {
    }

    override fun postPieceworkcollOk(scan:String,ishuancun:Boolean) {
        scanlist.remove(scan)
        edithuancun()
        if(scanlist.size > 0){
            if(printerSign != ""){
                P.postScanCodel(scanlist[0],printerSign)
            }
            P.postPieceworkcoll(scanlist[0],true)
            listAdapter.notifyDataSetChanged()
        }else{
            updialog?.dismiss()
            listAdapter.notifyDataSetChanged()
            Myutil.MyTost("上传成功")
        }
    }

    override fun postPieceworkcollNo(scan:String,ishuancun:Boolean) {
        updialog?.dismiss()
        if(!ishuancun){
            if(!scanlist.contains(scan)){
                scanlist.add(scan)
                edithuancun()
                listAdapter.notifyDataSetChanged()

            }

        }
    }

    override fun postScanCodelOk() {
        updialog?.dismiss()
    }

    override fun postScanCodelNo() {
        updialog?.dismiss()
    }

    //获取临时扫描数据
    fun gethuancun(){
        var data = sp.getString("scanlist","")
        if(data != "" && data != null){
            var list = data.split("&")
            for (item in list){
                scanlist.add(item)
            }
            listAdapter.notifyDataSetChanged()
        }
    }
    //保存灵石扫描数据
    fun edithuancun(){
        var data = "";
        for (i in 0 until scanlist.size){
            if(data != ""){
                data += "&"
            }
            data += scanlist[i]
        }
        editor.putString("scanlist",data)
        editor.commit()
    }

    //选择蓝牙
    override fun onClickBlue(position: Int, bluetoothDevice: BluetoothDevice) {
        updialog = Myutil.showupdatedialog(activity, "正在连接蓝牙", false)
        mainScannerSdk?.conectSppBlueTooth(bluetoothDevice)
    }

    override fun xialaOk() {
        Pull?.onHeaderRefreshComplete()
        pgadapter.notifyDataSetChanged()
    }

    override fun xialaNo() {
        Pull?.onHeaderRefreshComplete()
    }

    override fun shanglaOk() {
        Pull?.onFooterRefreshComplete()
        pgadapter.notifyDataSetChanged()
    }

    override fun shanglaNo() {
        Pull?.onFooterRefreshComplete()
    }

    override fun gainDataOk() {
        pgadapter.notifyDataSetChanged()
    }

    //选择蓝牙设备对话框
    fun blueDialog(){
        bluedialog = AlertDialog.Builder(context!!).create()
        bluedialog.setView(EditText(context!!))
        bluedialog.show()
        bluedialog.setContentView(R.layout.dialog_bluelist)
        val window = bluedialog.window
        val p = window?.attributes // 获取对话框当前的参数值
        p?.width = (sp.getInt("width", 0) * 0.9).toInt() // 宽度设置为屏幕的0.65
        window?.attributes = p
        bluedialog.bluelist_recycler.layoutManager = LinearLayoutManager(activity)
        bluedialog.bluelist_recycler.adapter = blueListAdapter

    }
    //蓝牙扫描枪回调
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun eventBbus(sdkMessage: SdkMessage) {
        when (sdkMessage.type) {
            SdkValue.SdkMessageType_Receve -> try {
                var data = String(sdkMessage.s, Charset.forName("utf-8")).replace("\r|\n".toRegex(), "")
                if(data.length>100){
                    Myutil.MyTost("扫描出错，数据的内容超过100字符")
                    return
                }
                Myutil.MyTost(data)
                if(lastcode == data){
                    Myutil.MyTost("与扫描的上一条数据相同，不上传")
                    return
                }
                FileUtils.playSound(R.raw.tishi);
                lastcode = data
                updialog = Myutil.showupdatedialog(activity, "正在上传", false)
                if(printerSign != ""){
                    P.postScanCodel(data,printerSign)
                }
                P.postPieceworkcoll(data,false)
            } catch (e: UnsupportedEncodingException) {
            }
            SdkValue.connectbt_fail -> {
                Myutil.MyTost("扫描枪连接失败")
            }
            SdkValue.connectbt_success-> {
                Myutil.MyTost("扫描枪连接成功")
                updialog?.dismiss()
                bluedialog.dismiss()
            }
        }
    }

    override fun onHeaderRefresh(view: PullToRefreshView?) {
        P.xiala()
    }

    override fun onFooterRefresh(view: PullToRefreshView?) {
        P.shangla()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(data==null||resultCode!= Activity.RESULT_OK){
            return
        }
        when (requestCode) {
            100 ->  {
                P.getPiecework()
            }
            1 -> if (resultCode == Activity.RESULT_OK) {
                val bundle = data.extras
                //显示扫描到的内容
                var s: String = bundle?.get("result") as String
                if(s.length>100){
                    Myutil.MyTost("扫描出错，数据的内容超过100字符")
                    return
                }
                updialog = Myutil.showupdatedialog(activity, "正在上传", false)
                P.postPieceworkcoll(s,false)
                FileUtils.playSound(R.raw.tishi);
            }
        }
    }

    override fun onItemLongClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long): Boolean {
        var c = context;
        if(c != null){
            val dialog = AlertDialog.Builder(c)
            dialog.setTitle("提示")
            dialog.setMessage("确定要删除这条扫描记录吗？")
            dialog.setPositiveButton("确定") { dialog, which ->
                scanlist.removeAt(position)
                edithuancun()
                listAdapter.notifyDataSetChanged()
                dialog.dismiss()
            }
            dialog.setNegativeButton("取消") { dialog, _ -> dialog.dismiss() }
            dialog.show()
        }
        return true
    }
}